<template>
  <div class="main-box">
    <TreeFilter
      label="data"
      id="attr"
      :title="t('accessControl.userManagement.departmentList')"
      :data="treeFilterData"
      :default-value="initParam.departmentId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getUserTreeList"
        :init-param="initParam"
        :request-auto="false"
        :data-callback="dataCallback"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button
            type="primary"
            v-auth="'add'"
            :icon="CirclePlus"
            @click="openDrawer(t('accessControl.userManagement.add'), undefined, undefined)"
          >
            {{ t("accessControl.userManagement.addUser") }}
          </el-button>
          <el-button type="primary" v-auth="'import'" :icon="Upload" plain @click="batchAdd">{{
            t("accessControl.userManagement.batchAddUser")
          }}</el-button>
          <el-button type="primary" v-auth="'export'" :icon="Download" plain @click="downloadFile">{{
            t("accessControl.userManagement.exportUserData")
          }}</el-button>
          <el-button type="primary" v-auth="'add'" plain @click="roleToGroup('角色赋予组', undefined, undefined)">
            角色赋予组
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button
            type="primary"
            v-auth="'view'"
            link
            :icon="View"
            @click="openDrawer(t('accessControl.userManagement.view'), scope.row, initParam.departmentId)"
          >
            {{ t("accessControl.userManagement.view") }}
          </el-button>
          <el-button
            type="primary"
            v-auth="'edit'"
            link
            :icon="EditPen"
            @click="openDrawer(t('accessControl.userManagement.edit'), scope.row, initParam.departmentId)"
          >
            {{ t("accessControl.userManagement.edit") }}
          </el-button>
          <el-button type="primary" link :icon="Refresh" @click="resetPass(scope.row)">{{
            t("accessControl.userManagement.resetPassword")
          }}</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">{{
            t("accessControl.userManagement.delete")
          }}</el-button>
        </template>
      </ProTable>
      <UserDrawer ref="drawerRef" />
      <ImportExcel ref="dialogRef" />
      <roleToGroupComponent ref="roleToGrouprRef" />
    </div>
  </div>
</template>
<script setup lang="ts" name="useTreeFilter">
import { ref, reactive, onMounted } from "vue";
import { User } from "@/api/interface";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/treeFilter.vue";
// import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";

import roleToGroupComponent from "@/views/accessControl/userManagement/components/roleToGroup.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import {
  getUserTreeList,
  deleteUser,
  editUser,
  addUser,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser,
  getUserDepartment,
  exportUser,
  updateRoleByGroupId
} from "@/api/modules/user";
import ImportExcel from "@/views/accessControl/userManagement/components/ImportExcel/index.vue";
import { tempUser, importUserData } from "@/api/modules/accessController";
// getUserStatus,
// getUserGender
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const router = useRouter();
onMounted(() => {
  getTreeFilter();
});

// 跳转详情页
const toDetail = () => {
  router.push(`/proTable/useTreeFilter/detail/123456?params=detail-page`);
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ departmentId: "" });

// 树形筛选切换
const changeTreeFilter = (val: object) => {
  // console.log(val.id.orgNo);
  // ElMessage.success("请注意查看请求参数变化 🤔");
  if (val instanceof Array) {
    return;
  }
  proTable.value!.pageable.pageNum = 1;
  if ((val as any).label === "全部") {
    initParam.departmentId = "";
    return;
  }
  if ((val as any).id.orgNo === "1") {
    initParam.departmentId = "";
  } else {
    initParam.departmentId = (val as any).id.orgNo;
  }
};
//部门列表
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getUserDepartment();
  if (data) {
    treeFilterData.value = data;
    initParam.departmentId = treeFilterData.value[0].attr.orgNo;
  }
};

const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "userId", label: "id", width: 80, sortable: true },
  {
    prop: "loginName",
    label: t("accessControl.userManagement.loginName"),
    search: {
      el: "input",
      tooltip: "输入登录账号定义类型名称",
      label: "登录账号",
      key: "userQueryDto.loginName"
    }
  },
  {
    prop: "firstName",
    label: t("accessControl.userManagement.firstName"),
    search: {
      el: "input",
      tooltip: "输入用户姓氏",
      label: "用户姓氏",
      key: "userQueryDto.firstName"
    }
  },
  {
    prop: "lastName",
    label: t("accessControl.userManagement.lastName"),
    search: {
      el: "input",
      tooltip: "输入用户名字",
      label: "用户名字",
      key: "userQueryDto.lastName"
    }
  },
  { prop: "orgName", label: t("accessControl.userManagement.organization") },
  { prop: "belongsGroupStr", label: t("accessControl.userManagement.technicalGroup"), width: 120 },
  {
    prop: "phone",
    label: t("accessControl.userManagement.phone"),
    search: {
      el: "input",
      tooltip: "输入电话",
      label: "电话",
      key: "userQueryDto.officePhone"
    }
  },
  {
    prop: "moblie",
    label: t("accessControl.userManagement.mobile"),
    width: 120,
    search: {
      el: "input",
      tooltip: "输入手机",
      label: "手机",
      key: "userQueryDto.mobilePhone"
    }
  },
  {
    prop: "email",
    label: t("accessControl.userManagement.email"),
    width: 120,
    search: {
      el: "input",
      tooltip: "输入邮件",
      label: "邮件",
      key: "userQueryDto.email"
    }
  },
  { prop: "roles", label: t("accessControl.userManagement.roles"), width: 80 },
  {
    prop: "userState",
    label: t("accessControl.userManagement.status"),
    width: 80,
    render: scope =>
      scope.row.userState ? t("accessControl.userManagement.enabled") : t("accessControl.userManagement.disabled")
  },
  {
    prop: "holidayStatus",
    label: t("accessControl.userManagement.holidayStatus"),
    width: 120,
    render: scope =>
      scope.row.holidayStatus === false ? t("accessControl.userManagement.onDuty") : t("accessControl.userManagement.onHoliday")
  },
  { prop: "operation", label: t("accessControl.userManagement.operation"), width: 300 }
]);

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(
    deleteUser,
    { ids: params.userId },
    t("accessControl.userManagement.deleteUserConfirm", { name: params.fullName })
  );
  proTable.value?.getTableList();
};

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  console.log(params);
  await useHandleData(
    resetUserPassWord,
    { "editUserPasswordDTO.loginName": params.loginName, "editUserPasswordDTO.resetPassword": "resetPassword" },
    t("accessControl.userManagement.resetPasswordConfirm", { name: params.fullName })
  );
  proTable.value?.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
  const params = {
    "userQueryDto.companyNo": 1,
    "userQueryDto.limit": 45,
    "userQueryDto.orgNo": "",
    "userQueryDto.belongsGroup": "",
    state: "all",
    "userQueryDto.loginName": "",
    "userQueryDto.firstName": "",
    "userQueryDto.lastName": "",
    "userQueryDto.email": "",
    "userQueryDto.mobilePhone": "",
    "userQueryDto.officePhone": "",
    "userQueryDto.orgType": ""
  };
  ElMessageBox.confirm(t("accessControl.userManagement.confirmExport"), t("accessControl.userManagement.tips"), {
    type: "warning"
  }).then(async () => {
    useDownload(exportUser, t("accessControl.userManagement.userList"), proTable.value?.searchParam);
    // const data = (await exportUser(params)) as any;
    // console.log(data);
    // try{
    //   const blob = new Blob([data]);
    //   const tempName = t("accessControl.userManagement.userList");
    //   const fileType = ".csv";
    //   // 兼容 edge 不支持 createObjectURL 方法
    //   if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, tempName + fileType);
    //   const blobUrl = window.URL.createObjectURL(blob);
    //   const exportFile = document.createElement("a");
    //   exportFile.style.display = "none";
    //   exportFile.download = `${tempName}${fileType}`;
    //   exportFile.href = blobUrl;
    //   document.body.appendChild(exportFile);
    //   exportFile.click();
    //   // 去除下载对 url 的影响
    //   document.body.removeChild(exportFile);
    //   window.URL.revokeObjectURL(blobUrl);
    // }catch(e){
    //   console.log(e)
    // }
  });
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: t("accessControl.userManagement.user"),
    tempApi: tempUser,
    importApi: importUserData,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<User.ResUserList> = {}, val: any) => {
  const params = {
    title,
    isView: title === t("accessControl.userManagement.view"),
    val,
    isadd: title != t("accessControl.userManagement.add"),
    row: { ...row },
    api:
      title === t("accessControl.userManagement.add")
        ? addUser
        : title === t("accessControl.userManagement.edit")
          ? editUser
          : undefined,
    getTableList: proTable.value?.getTableList
  };
  console.log(params.row);
  drawerRef.value?.acceptParams(params);
};

const roleToGrouprRef = ref<InstanceType<typeof roleToGroupComponent> | null>(null);
const roleToGroup = (title: string, row: Partial<User.ResUserList> = {}, val: any) => {
  const params = {
    title: "角色赋予组",
    isView: title === t("accessControl.userManagement.view"),
    val,
    isadd: title != t("accessControl.userManagement.add"),
    row: { ...row },
    api: updateRoleByGroupId,
    getTableList: proTable.value?.getTableList
  };
  console.log(params.row);
  roleToGrouprRef.value?.acceptParams(params);
};
</script>
